package com.fingard.dsp.bank.directbank.nbcb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Date;

/**
 * @author marlon
 * @date 2018/9/17
 */
public class NBCB01Receipt extends NBCB01Base implements IReceipt {

    //交易传入的数据
    private String receiptSaveToMainDir = "";
    @Override
    public RetAtsReceipt qryReceipt(final ReqQryReceipt p_reqReceipt) throws Exception {
        //余额查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    synchronized (NBCB01ScheduleTask.lockMutex){
                        download(p_reqReceipt);
                        retAts.respCode = "0";
                        retAts.respInfo = "后台处理中";
                        Thread.sleep(5000);
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public void download(ReqQryReceipt p_reqReceipt) {
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));

            XmlTextWriter xmlWriter = null;
            while (tmpIntFrom <= tmpIntTo) {
                Date fromDateStep = tmpCalendarFrom.getTime();
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                //发银行报文的XML对象
                xmlWriter = new XmlTextWriter();
                //写入通用的头部节点
                serviceId = "srv193_accountReceiptQuery";//客户回单信息查询
                writeCommonHeader(xmlWriter);
                if (!"".equals(bankFront.token)) {
                    xmlWriter.writeElementString("functionId", "srv193");
                    xmlWriter.writeElementString("functionName", "客户回单信息查询");
                    xmlWriter.writeStartElement("opReq");
                    String serialNo = getQryTransID() + (int) (Math.random() * 900 + 100);
                    xmlWriter.writeElementString("serialNo", serialNo);
                    xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(new Date()));

                    xmlWriter.writeStartElement("ReqParam");
                    xmlWriter.writeElementString("ZHHA", p_reqReceipt.actNum);//账户
                    xmlWriter.writeElementString("ZZH", "");//子账号
                    xmlWriter.writeElementString("CXRQ", Format.Date8Format.format(fromDateStep));//查询日期
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndElement();
                    String signXml = getDataSignData(xmlWriter);
                    if (signnatrue(signXml)) {
                        xmlWriter.writeElementString("signData", signature);
                        xmlWriter.writeEndDocument();
                        WriteBankLogLn("客户回单信息查询发送银行报文：" + xmlWriter.toXmlString());
                        String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));//发送银行
                        if (tmpStrRet[0].length() == 0) {
                            StringBuilder tmpSbMsg = new StringBuilder();
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                            if (tmpBkReader != null) {
                                String respCode = tmpBkReader.getFirstText("/NBCBEBankData/retCode");
                                String respInfo = tmpBkReader.getFirstText("/NBCBEBankData/errorMsg");
                                WriteBankLogLn("开始创建下载文件");
                                if (respCode != null && isActiveRetCode(respCode)) {
                                    while (tmpBkReader.read("/NBCBEBankData/opRep/opResult")) {
                                        String returnCode = tmpBkReader.readedXElement.getSingleText("YDDM");//应答代码
                                        String returnMsg = tmpBkReader.readedXElement.getSingleText("SBYY");//失败原因
                                        //String receiptCount = tmpBkReader.readedXElement.getSingleText("SHMU");//回单数量
                                        String receiptCode = tmpBkReader.readedXElement.getSingleText("JYXH");//查询序号
                                        if (returnCode != null && isActiveRetCode(returnCode)) {
                                            generateReceiptCodeFile(p_reqReceipt.actNum, Format.Date8Format.format(fromDateStep), serialNo);
                                        } else {
                                            WriteBankLogLn(returnMsg);
                                        }
                                        WriteBankLogLn("循环创建：receiptCode：" + serialNo);
                                    }
                                } else {
                                    WriteBankLogLn(respInfo);
                                }
                            } else {
                                WriteBankLogLn(tmpSbMsg.toString());
                            }
                        } else {
                            WriteBankLogLn(tmpStrRet[1]);
                        }
                    } else {
                        WriteBankLogLn(tmpSign[1]);
                    }
                } else {
                    WriteBankLogLn("登录失败");
                }
            }
        } catch (Exception e) {
            WriteBankLogLn(e.getMessage());
            e.printStackTrace();
        }
    }

    private void generateReceiptCodeFile(String actNum, String tranDate, String receiptCode) throws Exception {
        FileOutputStream fos = null;
        try {
            String path = FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "datafile" + File.separator + bankFront.code + File.separator + "receiptdatafile" + File.separator;
            String filePath = path + actNum + File.separator + actNum + "_" + Format.Date8Format.format(new Date()) + ".txt";
            File batFile = new File(filePath);
            if (!batFile.getParentFile().exists()) {
                batFile.getParentFile().mkdirs();
            }
            String fileContent = "";
            String newFileContent = actNum + "|" + tranDate + "|" + receiptCode;
            if (!batFile.exists()) {
                batFile.createNewFile();
            } else {
                fileContent = FtpUtil.getTextFromFile(filePath, getCharset());
                if (fileContent.contains(newFileContent)) {
                    return;
                }
            }
            fos = new FileOutputStream(batFile);
            fos.write(fileContent.concat(newFileContent + "\r\n").getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }
}
